﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Text;
using System.Text.RegularExpressions;

namespace DTcms.Core.Common.Helper
{
    public static class HttpHelper
    {
        public static IServiceCollection serviceCollection;
        public static Microsoft.AspNetCore.Http.HttpContext Current
        {
            get
            {
                object factory = serviceCollection.BuildServiceProvider().GetService(typeof(IHttpContextAccessor));
                Microsoft.AspNetCore.Http.HttpContext context = ((HttpContextAccessor)factory).HttpContext;
                return context;
            }
        }

        /// <summary>
        /// 发送GET请求
        /// </summary>
        /// <typeparam name="T">转换类型</typeparam>
        /// <param name="url">接口地址</param>
        /// <returns>T类型</returns>
        public static T Get<T>(string url, bool isCache = true) where T : class
        {
            //读取缓存
            if (isCache)
            {
                var model = MemoryCacheHelper.Get<T>(url);
                if (model != null)
                {
                    return model;
                }
            }
            var baseApi = $"{Current.Request.Scheme}://{Current.Request.Host}/api"; //获取API地址
            var expired = int.Parse(Appsettings.GetValue(new string[] { "ApiConfig", "Expired" }));
            var jsonData = RequestHelper.Get($"{baseApi}{url}");
            var result = JsonHelper.ToJson<T>(jsonData);
            //存入缓存
            if (isCache && result != null)
            {
                MemoryCacheHelper.Set(url, result, new TimeSpan(0, 0, expired));
            }
            return result;
        }

        /// <summary>
        /// 替换内容图片地址为API绝对路径
        /// </summary>
        public static string ReplaceImagesPath(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                return string.Empty;
            }
            var baseApi = $"{Current.Request.Scheme}://{Current.Request.Host}/api"; //获取API地址
            Regex reg = new Regex("IMG[^>]*?src\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^\']*)')", RegexOptions.IgnoreCase);
            MatchCollection m = reg.Matches(content);
            foreach (Match math in m)
            {
                string imgUri = math.Groups[1].Value;
                if (imgUri.StartsWith("http://") || imgUri.StartsWith("https://"))
                {
                    continue;
                }
                string newImgPath = baseApi + imgUri;
                content = content.Replace(imgUri, newImgPath);
            }
            return content;
        }
    }
}
